<?php

namespace Frieza\Modules\Live\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\course\AdmCourse;
use function Clue\StreamFilter\fun;
use Doraemon\cache\Live\WhiteUser;
use Doraemon\model\Live\LiveRoom as mLiveRoom;
use Doraemon\model\Live\LiveRoomExtend as mLiveRoomExtend;
use Doraemon\service\Live\AdmLive;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\Live\AdmColumn;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $condition = $this->_index_condition($request);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['ORDER'] = ['room_id' => 'DESC'];
        $result = AdmLive::getRoomList($where);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);
        Admin::script($this->closeScript());
        Admin::script($this->delScript());
        Admin::script($this->backScript());
        //直播栏目列表
        $column_list= AdmColumn::columnList();
        $column_list[0] = '无栏目';
        //直播栏目列表
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel ,$column_list) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) use ($column_list){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) use ($column_list) {
                        $filter->equal('room_id', '房间id');
                        $filter->equal('live_status', '直播状态')->select(mLiveRoom::STATUS_DESC);
                        $filter->equal('room_column', '直播栏目')->select($column_list);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('room_title', '直播标题');
                        $filter->between('live_time', '直播时间')->datetime();
                        $filter->equal('live_type', '直播方式')->select(mLiveRoom::LIVE_TYPE);

                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '房间ID')->width(70);
                $grid->column('room_title', '直播标题')->display(function () {
                    $html = $this->room_title ;
                    if($this->op_description){
                        $op_desc = str_replace('#&' , '<br/>',$this->op_description);
                        $html.='<br/><a tabindex="0" role="button" style="display:inline-block;" data-toggle="popover" data-trigger="hover" title="" target="_blank" data-html="true" data-container="body" data-content="'.$op_desc.'" data-original-title="运营语"><i class="fa fa-question-circle" style="color:blue;">查看运营语</i></a>';
                    }
                    $html.='<br/><br/><a href="' . url('/admin/live/chest/' . $this->id) . '/" class="btn btn-default">百宝箱</a>';
                    $html.='</br><a href="' . url('/admin/live/index/' . $this->id.'/banner') . '/" class="btn btn-default">广告牌</a>';
                    return $html;
                })->width(100);
                $grid->column('uid', '直播用户')->display(function () use($column_list) {
                    $display = [];

                    $display[] =  '<p>' . $this->uid . '</p>' . '<p>' . $this->user_nick . '</p>';
                    if($this->anchor_uid){
                        $display[] = '<p>连麦主播：' . $this->anchor_uid . '</p>' . '<p>' . $this->anchor_user_nick . '</p>';

                    }

                    return implode("<br/>" , $display);
                })->width(100);
                $grid->column('room_column', '栏目')->display(function () use($column_list) {
                    $display = [];

                    $display[] =  '<p>' . $column_list[$this->room_column] .'</p>';

                    return implode("<br/>" , $display);
                })->width(100);


                $grid->column('start_time', '开始时间')->width(80);
                $grid->column('end_time', '结束时间')->width(80);
                $grid->column('play_back', '支持回看')->display(function () {
                    return $this->play_back ? '是' : '否';
                })->width(80);
                $grid->column('preview_img', '预告图')->image($this->preview_img, 100, 100);
                $grid->column('back_img', '回看图')->image($this->preview_img, 100, 100);
                $grid->column('live_type', '直播信息')->display(function () {
                    $cloumn_type = mLiveRoom::CLOUMN_TYPE[$this->column_identy] ? : '无';
                    $display = '';
                    $display .=  '<p>' . mLiveRoom::LIVE_TYPE[$this->live_type] . '</p>' . '<p>悬浮框:' .$cloumn_type  . '</p>';
                    $display.= '<p>' . mLiveRoom::SCREEN_TYPE[$this->is_full_screen] . '</p>' . '<p>' . $this->anchor_user_nick ;
                    return $display;
                })->width(80);

                $grid->column('pull_url', '播放地址')->display(function (){
                    $display  = '';
                    if($this->live_type == mLiveRoom::LIVE_TYPE_BUSS && $this->pull_url){
                        $display.= '<p>' . $this->pull_url . '</p>' ;
                    }
                    return $display;
                })->width(80);
                $grid->column('status_desc', '直播状态')->width(80);
                $grid->column('addtime', '添加时间')->width(80);
                $grid->column('edittime', '编辑时间')->width(80);
                $grid->column('admin_id', '操作人')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                })->width(100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    if ($actions->row->play_back) {
                        $actions->prepend('&nbsp;<a class="fa cancelBack-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消回看</a><br/>');
                    } else if ($actions->row->play_back == 0) {
                        $actions->prepend('&nbsp;<a class="fa openBack-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">恢复回看</a><br/>');
                    }
                    if ($actions->row->live_status == mLiveRoom::STATUS_NORMAL) {
                        $actions->prepend('&nbsp;<a class="fa del-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消</a><br/>');
                    } else if ($actions->row->live_status == mLiveRoom::STATUS_LIVING) {
                        if($actions->row->anchor_uid){
                            if($actions->row->anchor_status == 'active'){
                                $actions->prepend('&nbsp;<a class="fa close-lianmai-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">禁止连麦</a><br/>');
                            }
                            if($actions->row->anchor_status == "forbid"){
                                $actions->prepend('&nbsp;<a class="fa resume-lianmai-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">恢复连麦功能</a><br/>');
                            }
                        }
                        $actions->prepend('&nbsp;<a class="fa close-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">关闭</a><br/>');

                    }


                    if($actions->row->live_type == mLiveRoom::LIVE_TYPE_BUSS && $actions->row->live_status == mLiveRoom::STATUS_NORMAL){
                        $actions->prepend('&nbsp;<a class="fa start-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">开始直播</a><br/>');

                    }
                    $actions->disableView();
                    $actions->disableDelete();
                });
                //$grid->setActionClass(Grid\Displayers\DropdownActions::class);
            }
        );
        $tab = new Tab();
        $tab->add('直播列表', $gridList->render(), true);
        $tab->addLink('直播中', url('admin/live/index/living'));
        return $content->header('直播列表')->breadcrumb(
            ['text' => '直播列表'])
            ->row($tab);
    }

    public function living(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['live_status'] = mLiveRoom::STATUS_LIVING;
        $where['ORDER'] = ['room_id' => 'DESC'];
        $result = AdmLive::getRoomList($where);
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $pageSize
        ]);
        Admin::script($this->createGroupScript());
        Admin::script($this->closeScript());
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '房间ID')->width(70);
                $grid->column('room_title', '直播标题')->width(100);
                $grid->column('uid', '直播用户')->display(function () {
                    return '<p>' . $this->uid . '</p>' . '<p>' . $this->user_nick . '</p>';
                });
                $grid->column('start_time', '开始时间')->width(120);
                $grid->column('end_time', '结束时间')->width(120);
                $grid->column('preview_img', '预告图')->image($this->preview_img, 100, 100);
                $grid->column('back_img', '回看图')->image($this->preview_img, 100, 100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->prepend('&nbsp;<a class="fa close-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">关闭</a>');
                    $url = Hhzurl::h5ShareLive($actions->row->id);
                    $actions->prepend('&nbsp;&nbsp;<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'360px\', \'640px\'],
                                content: \'' . $url . '\'
                            });">预览</a>');
                    if (!$actions->row->group_id) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa group-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">创建群聊</a>');
                    }
                    $actions->disableView();
                    $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->addLink('直播列表', url('admin/live/index'), false);
        $tab->add('直播中', $gridList->render(), true);
        return $content->header('直播列表')->breadcrumb(
            ['text' => '直播列表'])
            ->row($tab);
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $id => $sort) {
            AdmCourse::sort($sort, $id);
        }
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $header = '添加直播';
        if ($id) {
            $header = '编辑直播';
        }
        $info = $id ? AdmLive::getRoom($id) : [];
        if ($info && $id && $info['live_status'] == mLiveRoom::STATUS_NORMAL && !$info['group_id']) {
            $content->row('<div class="btn-group pull-left" style="margin-right: 10px"><a href="javascript:void(0)" class="btn btn-sm btn-success group-data" data-id="' . $id . '"><i class="fa "></i>&nbsp;&nbsp;创建群聊</a></div>');
            $content->row('<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;如果使用第三方推流工具，需要创建群聊，直播间才能聊天。请在直播前创建！</span>');
            Admin::script(self::createGroupScript());
        }
        //直播栏目列表
        $column_list= AdmColumn::columnList();
        $column_list[0] = '无栏目';
        //直播栏目列表
        $form = new Form($info);
        $form->hidden('room_id');
        if ($info) {
            if($info['live_type'] == mLiveRoom::LIVE_TYPE_NORMAL){
                $form->text('stream_id', '直播流')->readonly();
                $form->text('push_url', '推流地址')->readonly();
                $form->text('pull_url', '拉流地址')->readonly();
            }
            $form->text('live_status_desc', '直播状态')->readonly();
            if (!empty($info['group_id'])) {
                $form->text('group_id', '群聊Id')->readonly();
            }
        }
        $form->select('room_column', '直播栏目')->options($column_list);
       // $form->select('live_type', '直播方式')->options(mLiveRoom::LIVE_TYPE)->default(mLiveRoom::LIVE_TYPE_NORMAL) ;
        $form->fieldChange('live_type', '直播方式', $form)
            ->options(mLiveRoom::LIVE_TYPE)
            ->default(mLiveRoom::LIVE_TYPE_NORMAL)
            ->callablePreCommon(function (Form $form) {
            })->callableMap([
                mLiveRoom::LIVE_TYPE_NORMAL  => function (Form $form) {},
                mLiveRoom::LIVE_TYPE_BUSS=> function (Form $form) {
                    $form->text('pull_url', '推流地址');
                }
            ]);

        $form->select('is_full_screen', '是否全屏')->options(mLiveRoom::SCREEN_TYPE)->default(mLiveRoom::FULL_SCREEN);

        $form->select('column_identy', '浮窗类型')->options(mLiveRoom::CLOUMN_TYPE)->default(0);

        $form->text('room_title', '直播标题')->required();
        $form->text('room_subtitle', '直播副标题')->help('最多输入10个字')->attribute('maxlength', '10');

        $form->textarea('op_description', '运营推荐语')->help("换行用  <span style='color:red'>'#&'</span>  代替");
        if ($info && in_array($info['live_status'], [ mLiveRoom::STATUS_CLOSE, mLiveRoom::STATUS_DELETE])) {
            $form->text('uid', '直播uid')->required()->help('当前状态不支持更改直播uid')->readonly();
            $form->datetimeRange('start_time', 'end_time', '直播时间')->required('不能为空')
                ->attribute('autocomplete', 'off')
                ->help('当前状态不支持修改时间')
                ->readonly();
        } else {

            $form->text('uid', '直播uid')->required();
            $form->datetimeRange('start_time', 'end_time', '直播时间')->required('不能为空')->attribute('autocomplete', 'off');
        }
        $form->text('room_tag', '标签')->help('多个标签，请以英文逗号(,)分隔。最多5个字，累计最多8个字');
        $form->text('anchor_uid', '连麦uid');
        $form->radio('play_back', '支持回放')->options([1 => '支持', 0 => '不支持'])->default(1);
        $form->radio('is_show', '是否公开')->options([1 => '公开', 0 => '不公开'])->default(1);
        if ($info && in_array($info['live_status'], [mLiveRoom::STATUS_LIVING, mLiveRoom::STATUS_CLOSE, mLiveRoom::STATUS_DELETE])) {
            $form->number('question_point', '提问需要积分')->default(0)->help('当前状态不支持修改')->readonly();
            $form->textarea('room_admin', '场控')->help('uid,用英文逗号分隔')->help('当前状态不支持修改')->readonly();
        } else {
            $form->number('question_point', '提问需要积分')->default(0);
            $form->textarea('room_admin', '场控')->help('uid,用英文逗号分隔');
        }
        $form->imgUpload('preview_img', '预告图')->help('必传');
        $form->imgUpload('back_img', '回放图')->help('必传');
        $form->imgUpload('preview_info_img', '预告详情图');
        $form->action(url('admin/live/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '直播列表', 'url' => url('admin/live/index')],
            ['text' => $header]);
    }

    public function banner(Request $request, Content $content, $id = 0)
    {
        $info = mLiveRoom::getByWhere(['room_id' => $id]);
        $extendInfo = mLiveRoomExtend::getByWhere(['room_id' => $id]);
        $info['link'] = [
            'link_type' => $extendInfo ? $extendInfo['link_type'] : '',
            'link_params' => $extendInfo ? $extendInfo['link_params'] : '',
        ];
        $info['banner'] = $extendInfo ? $extendInfo['banner'] : '';
        $form = new Form($info);
        $form->hidden('room_id');
        $form->imgUpload('banner', 'banner图片')->help('必传');
        $form->linkSelect('link');
        $form->action(url('admin/live/saveBanner'));
        $content->row($form);
        return $content->header('配置广告牌')->breadcrumb(
            ['text' => '直播列表', 'url' => url('admin/live/index')],
            ['text' => '配置广告牌']);
    }

    public function saveBanner(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['room_id']) ? $params['room_id'] : 0;
            $info = mLiveRoom::getByWhere(['room_id' => $id]);
            if (!$info) {
                throw new \Exception('不存在的直播id');
            }
            if (!$params['banner']) {
                throw new \Exception('banner图片必传');
            }
            $data = [
                'banner' => $params['banner'],
                'link_type' => $params['link_type'],
                'link_params' => json_encode($params['link_params'], JSON_UNESCAPED_UNICODE)
            ];
            $extendInfo = mLiveRoomExtend::getByWhere(['room_id' => $id]);
            if (!$extendInfo) {
                $data['room_id'] = $id;
                $result = mLiveRoomExtend::insertData($data);
            } else {
                $result = mLiveRoomExtend::updateData($data, ['room_id' => $id]);
            }
            if ($result) {
                return redirect(url('/admin/live/index'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['room_id']) ? $params['room_id'] : 0;
            $roomInfo = $id ? mLiveRoom::getByWhere(['room_id' => $id]) : [];
            $data = [
                'room_title' => $params['room_title'],
                'room_subtitle' => $params['room_subtitle'],
                'room_type' => $params['room_type'] ? : 0,
                'uid' => $params['uid'],
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'room_tag' => str_replace('，', ',', trim($params['room_tag'])),
                'play_back' => $params['play_back'] ? $params['play_back'] : 0,
                'is_show' => $params['is_show'] ? $params['is_show'] : 0,
                'question_point' => $params['question_point'] ? $params['question_point'] : 0,
                'room_admin' => str_replace('，', ',', trim($params['room_admin'])),
                'preview_img' => $params['preview_img'] ? $params['preview_img'] : '',
                'preview_info_img' => $params['preview_info_img'] ? $params['preview_info_img'] : '',
                'back_img' => $params['back_img'] ? $params['back_img'] : '',
                'admin_id' => Admin::user()->id,
                'anchor_uid' => trim($params['anchor_uid']) ? : 0,
                'op_description' => $params['op_description'] ? : '',
                'live_type' => $params['live_type'] ? : 0,
                'pull_url' => $params['pull_url'] ? : '',
                'column_identy' => $params['column_identy'] ?  : 0,
                'room_column' => $params['room_column'] ? : 0,
                'is_full_screen' => $params['is_full_screen'],
            ];
            if ($roomInfo && in_array($roomInfo['live_status'], [mLiveRoom::STATUS_LIVING, mLiveRoom::STATUS_CLOSE, mLiveRoom::STATUS_DELETE])) {
                //当前状态下，不能修改这些信息
                unset($data['uid']);
                unset($data['start_time']);
//                unset($data['end_time']);
                unset($data['question_point']);
                unset($data['room_admin']);
            } else {
                if (empty($data['uid'])) {
                    throw new \Exception('必须设置直播uid');
                }
                if (empty($data['start_time'])) {
                    throw new \Exception('必须设置开始时间');
                }
                if (empty($data['end_time'])) {
                    throw new \Exception('必须设置结束时间');
                }
                if ($data['start_time'] <= time()) {
                    throw new \Exception('开始时间必须大于当前时间');
                }
                if ($data['start_time'] >= $data['end_time']) {
                    throw new \Exception('开始时间必须小于结束时间');
                }
            }
            if (empty($data['room_title'])) {
                throw new \Exception('必须设置直播标题');
            }
            if (empty($data['preview_img'])) {
                throw new \Exception('必须上传预告图');
            }
            if (empty($data['back_img'])) {
                throw new \Exception('必须上传回看图');
            }
            $result = AdmLive::editRoom($data, $id);
            if ($result) {
                $url = url('/admin/live/index');
                return redirect($url)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function white(Request $request, Content $content)
    {
        $uids = WhiteUser::getWhiteUsers();
        $uids = $uids ? implode(',', $uids) : '';
        $info = $uids ? ['uids' => $uids] : [];
        $form = new Form($info);
        $form->textarea('uids', '白名单uid')->help('英文逗号隔开');
        $form->action(url('admin/live/') . '/index/saveWhite');
        return $content->header('直播白名单')->breadcrumb(
            ['text' => '直播列表', 'url' => url('admin/live/index')],
            ['text' => '直播白名单'])->row($form->render());
    }


    public function saveWhite(Request $request)
    {
        try {
            $uids = $request->input('uids', '');
            $uids = str_replace('，', ',', trim($uids));
            $uids = explode(',', $uids);
            WhiteUser::setWhiteUsers($uids);
            return redirect(url('/admin/live/index/'))->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage(), $e->getFile(), $e->getLine());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    public function _index_condition($request)
    {
        $response = [];
        if (isset($request['room_id']) && ($request['room_id'] > 0)) {
            $response['room_id'] = $request['room_id'];
            return $response;
        }
        if (isset($request['room_title']) && strlen($request['room_title']) > 0) {
            $response['room_title[~]'] = $request['room_title'];
        }
        if (isset($request['live_status']) && strlen($request['live_status']) > 0) {
            $response['live_status'] = $request['live_status'];
        }
        if (isset($request['room_column']) ) {
            $response['room_column'] = $request['room_column'];
        }
        if (isset($request['live_time'])) {
            if (isset($request['live_time']['start']) && strlen($request['live_time']['start']) > 0) {
                $response['start_time[>=]'] = strtotime($request['live_time']['start']);
            }
            if (isset($request['live_time']['end']) && strlen($request['live_time']['end']) > 0) {
                $response['start_time[<=]'] = strtotime($request['live_time']['end']);
            }
        }
        if (isset($request['live_type']) ) {
            $response['live_type'] = $request['live_type'];
        }
        return $response;
    }

    public function close(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                AdmLive::closeRoom($roomId, $adminId);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 关闭成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '关闭失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    //开启直播
    public function start(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {

                AdmLive::startRoom($roomId , $adminId);

                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 开启成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '开启失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    //关闭连麦
    public function closelianmai(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                AdmLive::closeLianmai($roomId, $adminId);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 关闭连麦成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '关闭连麦失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    //恢复连麦
    public function resumelianmai(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                AdmLive::ResumeLianmai($roomId, $adminId);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 恢复连麦主播成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '恢复连麦失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function cancelBack(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                mLiveRoom::updateData(['play_back' => 0], ['room_id' => $roomId]);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 取消回看成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '取消回看失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function openBack(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                mLiveRoom::updateData(['play_back' => 1], ['room_id' => $roomId]);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 恢复回看成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '恢复回看失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function del(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                AdmLive::delRoom($roomId, $adminId);
                $success = [
                    'title' => '直播 ID: ' . $roomId . ' 取消成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '取消失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function createGroup(Request $request, $id = 0)
    {
        if (!$id) {
            $id = $request->input('id');
        }
        try {
            $adminId = Admin::user()->id;
            $roomId = $request->input('id', 0);
            if ($roomId) {
                AdmLive::createImGroup($roomId);
                $success = [
                    'title' => '创建群聊成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '创建群聊失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    private function closeScript()
    {
        return <<<SCRIPT
        $('.close-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要关闭当前直播:'+id+'吗？')){
                let url = 'close'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
        
         $('.start-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要开启当前直播:'+id+'吗？')){
                let url = 'start'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
        $('.close-lianmai-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要禁止当前连麦流:'+id+'吗？')){
                let url = 'closelianmai'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
      });
      $('.resume-lianmai-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要恢复连麦流:'+id+'吗？')){
                let url = 'resumelianmai'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
      });
SCRIPT;
    }

    private function delScript()
    {
        return <<<SCRIPT
        $('.del-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要取消当前直播:'+id+'吗？')){
                let url = 'del'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
SCRIPT;
    }

    private function backScript()
    {
        return <<<SCRIPT
        $('.cancelBack-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要取消当前直播:'+id+'的回看吗？')){
                let url = 'cancelBack'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
        $('.openBack-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要恢复当前直播:'+id+'的回看吗？')){
                let url = 'openBack'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            }
        });
SCRIPT;
    }

    private function createGroupScript()
    {
        return <<<SCRIPT
        $('.group-data').unbind('click').click(function(){
            var id= $(this).data('id');
                let url = 'createGroup'
                let params = {id:id}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
        });
SCRIPT;
    }

}